package com.example.blog.modules.monitor.repository;

import com.example.blog.modules.monitor.entity.MetricsHistory;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.time.LocalDateTime;
import java.util.List;

public interface MetricsHistoryRepository extends JpaRepository<MetricsHistory, Long> {
    
    /**
     * 获取指定时间范围内的监控历史记录
     */
    List<MetricsHistory> findByTimestampBetweenOrderByTimestampAsc(LocalDateTime start, LocalDateTime end);
    
    /**
     * 获取最近N条记录
     */
    List<MetricsHistory> findTopNByOrderByTimestampDesc(@Param("n") int n);
    
    /**
     * 删除指定时间之前的历史记录
     */
    void deleteByTimestampBefore(LocalDateTime timestamp);
    
    /**
     * 获取系统CPU使用率的平均值
     */
    @Query("SELECT AVG(m.systemCpuUsage) FROM MetricsHistory m WHERE m.timestamp BETWEEN :start AND :end")
    Double getAverageSystemCpuUsage(@Param("start") LocalDateTime start, @Param("end") LocalDateTime end);
    
    /**
     * 获取堆内存使用的平均值
     */
    @Query("SELECT AVG(m.heapMemoryUsed) FROM MetricsHistory m WHERE m.timestamp BETWEEN :start AND :end")
    Double getAverageHeapMemoryUsed(@Param("start") LocalDateTime start, @Param("end") LocalDateTime end);
} 